﻿using FinalYear.Helpers;
using System;
using System.ComponentModel;
using System.IO.Ports;

namespace FinalYear.OpticalFlow.Classes
{
    /// <summary>
    /// Sonar Sensor Class
    /// </summary>
    public class SonarSensor : Sensor
    {
        private SerialPort currentPort;
        private IContainer components;
        private int sonarDistance;

        public string distance { get; set; }

        /// <summary>
        /// Initializes a new instance of the <see cref="SonarSensor" /> class.
        /// </summary>
        public SonarSensor()
        {
            this.components = new Container();
            this.currentPort = new SerialPort(components);
            this.currentPort.PortName = Constants.DEFAULTCOMPORT;
            this.currentPort.BaudRate = Constants.SONARBAUDRATE;

            this.CheckPortEnableDTR();
        }

        private void CheckPortEnableDTR()
        {
            try
            {
                this.currentPort.Open();
                if (!this.currentPort.IsOpen)
                {
                    return;
                }

                this.currentPort.DtrEnable = true;

                // callback for text coming back from the arduino
                this.currentPort.DataReceived += OnReceived;
            }
            catch (Exception)
            {
                // Log the exception in the exception logger
            }
        }

        /// <summary>
        /// Called when [received].
        /// </summary>
        /// <param name="sender">The sender.</param>
        /// <param name="e">The <see cref="SerialDataReceivedEventArgs" /> instance containing the event data.</param>
        private void OnReceived(object sender, SerialDataReceivedEventArgs e)
        {
            try
            {
                this.distance = string.Empty;

                // write out text coming back from the arduino
                this.distance = this.currentPort.ReadExisting();
                int.TryParse(this.distance, out this.sonarDistance);
            }
            catch (Exception) { }
        }

        public bool ObstacleInRange()
        {
            if ((this.sonarDistance <= Constants.MINIMUMSONARDETECTIONRANGE) && (this.sonarDistance > Constants.BASESONARDETECTIONRANGE))
            {
                return true;
            }
            return false;
        }

        internal override bool CheckDiagnostic()
        {
            throw new NotImplementedException();
        }
    }
}